﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BCZadmin.Model;
using BCZadmin.Helper;
using System.Net;
using System.IO;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Runtime.InteropServices;

namespace BCZadmin
{
    public partial class Main : Form
    {
        #region 窗体弹出或消失效果相关设置
        //窗体弹出或消失效果
        [DllImport("user32.dll", EntryPoint = "AnimateWindow")]
        private static extern bool AnimateWindow(IntPtr handle, int ms, int flags);
        public const Int32 AW_HOR_POSITIVE = 0x00000001;
        public const Int32 AW_HOR_NEGATIVE = 0x00000002;
        public const Int32 AW_VER_POSITIVE = 0x00000004;
        public const Int32 AW_VER_NEGATIVE = 0x00000008;
        public const Int32 AW_CENTER = 0x00000010;
        public const Int32 AW_HIDE = 0x00010000;
        public const Int32 AW_ACTIVATE = 0x00020000;
        public const Int32 AW_SLIDE = 0x00040000;
        public const Int32 AW_BLEND = 0x00080000;
        //窗体弹出或消失效果
        #endregion
        #region 窗体移动相关
        [DllImport("user32.dll", EntryPoint = "SendMessageA")]
        private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);

        [DllImport("user32.dll")]
        private static extern int ReleaseCapture();
        private const int WM_NCLBUTTONDOWN = 0XA1;   //.定义鼠標左鍵按下
        private const int HTCAPTION = 2;
        //窗体移动
        #endregion
        private AdminInf admininf;
        private string BaseUrl = "http://123.207.86.30/public/index.php/db";
        private string PicBase = "http://123.207.86.30/public/pic/";
        private string MusicBase = "http://123.207.86.30/public/mp3/";
        private string VideoBase = "http://123.207.86.30/public/mp4/";
        private ModelForm edit;//编辑窗体
        private SynchronizationContext m_SyncContext ;//ui线程上下文
        public delegate string GitPicdeletegate(string a,string typename);//获取图片委托
        #region 相关字典
        private Dictionary<string, string> Filetype = new Dictionary<string, string>();//文件后缀名对应中文名
        private Dictionary<ListView, string> controller = new Dictionary<ListView, string>();//lv对应的控制器字典
        private Dictionary<ListView, DbModel> model = new Dictionary<ListView, DbModel>();//lv对应的实体类
        private Dictionary<string, Dictionary<string, Control>> putcon = new Dictionary<string, Dictionary<string, Control>>();//字段输入控件字典;
        public Dictionary<string, Dictionary<string, string>> queryfile = new Dictionary<string, Dictionary<string, string>>();//实体类中能查询的字段及对比方式(like,==)
        #endregion
        //内嵌窗体控件参数
        int x = 80;
        int y = 40;
        int YDistance = 40;
        public Main(AdminInf admininf)
        {
            InitializeComponent();
            this.admininf = admininf;
            //获取上下文 用于子线程更改ui
            m_SyncContext = SynchronizationContext.Current;
        }
        private void Main_Load(object sender, EventArgs e)
        {
            //显示admin用户名
            SL_Adminname.Text += admininf.A_Name;
            ///加载listview的head
            LoadLvhead();
            ///在panel控件中添加model窗体
            edit = new ModelForm(this.BaseUrl, this);
            edit.FormBorderStyle = FormBorderStyle.None;
            edit.AutoScroll = true;
            edit.TopLevel = false;
            edit.Dock = DockStyle.Fill;
            //指定父容器
            edit.Parent = this.PL_edit;
            PL_edit.Controls.Clear();
            PL_edit.Controls.Add(edit);
            edit.Show();
            ///加载当前page数据
            LoadPage("getall");
            LB_status.Text = "登陆时间:" + DateTime.Now.ToString();
            //文件后缀显示的中文名
            Filetype.Add(".jpg", "图片");
            Filetype.Add(".mp3", "音频");
            Filetype.Add(".mp4", "视频");
            //等到窗体加载完成  弹出效果
            AnimateWindow(this.Handle, 300, AW_CENTER);
        }
        /// <summary>
        /// 刷新指定页面
        /// </summary>
        /// <param name="Pagename"></param>
        public void LoadPage( string Methodurl, Dictionary<string, string> param = null)
        {
            var Pagename=TC_All.SelectedTab.Name;
            Methodurl = "/" + controller[GetShowListView()] +"/"+ Methodurl;
            switch (Pagename)
            {
                case "TP_word":
                    var list_word = GetListDate<WordInf>(Methodurl, param);
                    LoadListView<WordInf>(LV_word, list_word);
                    ; break;
                case "TP_wordGroup":
                    var list_Group = GetListDate<WordGroupInf>(Methodurl, param);
                    LoadListView<WordGroupInf>(LV_Group, list_Group);
                    ; break;
                case "TP_plan":
                    var list_plan = GetListDate<PlanInf>(Methodurl, param);
                    LoadListView<PlanInf>(LV_Plan, list_plan);
                    ; break;
                case "TP_User":
                    var list_user = GetListDate<UserInf>(Methodurl, param);
                    LoadListView<UserInf>(LV_user, list_user);
                    ; break;
                case "TP_Remenber":
                    var list_remenber = GetListDate<RemenberInf>(Methodurl, param);
                    LoadListView<RemenberInf>(LV_Remenber, list_remenber);
                    ; break;
                case "TP_Admin":
                    var list_Admin = GetListDate<AdminInf>(Methodurl, param);
                    LoadListView<AdminInf>(LV_Admin, list_Admin);
                    ; break;
            }
        }
        private void TC_all_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadPage( "getall");
            ClearFrom(edit);
        }
        /// <summary>
        /// 初始化listview  和相关信息字典
        /// </summary>
        private void LoadLvhead()
        {
            //word
            LV_word.View = View.Details;
            LV_word.FullRowSelect = true;//设置选中一行
            LV_word.HideSelection = false;//设置焦点失去就不再选中
            controller.Add(LV_word, "wordcontrol");
            model.Add(LV_word, new WordInf());
            LV_word.Columns.Add("id", 50, HorizontalAlignment.Center);
            LV_word.Columns.Add("单词", 100, HorizontalAlignment.Center);
            LV_word.Columns.Add("汉语意义", 100, HorizontalAlignment.Center);
            LV_word.Columns.Add("象形图片", 100, HorizontalAlignment.Center);
            LV_word.Columns.Add("发音", 100, HorizontalAlignment.Center);
            LV_word.Columns.Add("英语例句", 100, HorizontalAlignment.Center);
            LV_word.Columns.Add("单词视频", 100, HorizontalAlignment.Center);
            LV_word.Columns.Add("汉语例句", 100, HorizontalAlignment.Center);
            LV_word.Columns.Add("音标", 100, HorizontalAlignment.Center);
            putcon.Add(new WordInf().GetType().ToString(),
             new Dictionary<string, Control>{
            {"W_Id",new TextBox()},
            {"W_Name", new TextBox()},
            {"W_Chinese", new TextBox()},
            {"W_PicPath", new PictureBox()},
            {"W_VoicePath", new Button(){
                Size=new Size(59, 55),
                Tag=new Dictionary<string,string>(){
                 {"local",""},
                 {"server",""}
                },
                BackgroundImage=Image.FromFile(Application.StartupPath + @"\pic\"  + "play.JPG"),
                BackgroundImageLayout=ImageLayout.Stretch,
            }},
            {"W_ExSentence", new RichTextBox()},
            {"W_CExSentence", new RichTextBox()},
            {"W_Video", new Button(){ Text="打开单词视频" ,Tag=new Play()}},
            {"W_SoundMark", new TextBox()}
            }
               );
            queryfile.Add(new WordInf().GetType().ToString(),
                new Dictionary<string, string>{
            {"W_Name", "like"},
            {"W_Chinese","like"},
            {"W_SoundMark", "like"}                
                }
                );
            //wordgroup
            LV_Group.View = View.Details;
            LV_Group.FullRowSelect = true;
            LV_Group.HideSelection = false;
            controller.Add(LV_Group, "wordgroupcontrol");
            model.Add(LV_Group, new WordGroupInf());
            LV_Group.Columns.Add("id", 50, HorizontalAlignment.Center);
            LV_Group.Columns.Add("单词组名", 100, HorizontalAlignment.Center);
            LV_Group.Columns.Add("单词id集合", 100, HorizontalAlignment.Center);
            LV_Group.Columns.Add("组图片", 100, HorizontalAlignment.Center);
            LV_Group.Columns.Add("单词类别", 100, HorizontalAlignment.Center);
            LV_Group.Columns.Add("介绍", 100, HorizontalAlignment.Center);
            LV_Group.Columns.Add("数量", 100, HorizontalAlignment.Center);
            LV_Group.Columns.Add("发布时间", 150, HorizontalAlignment.Center);
            putcon.Add(new WordGroupInf().GetType().ToString(),
              new Dictionary<string, Control>{
             {"WG_Id",new TextBox()},
             {"WG_Name", new TextBox()},
             {"WG_WordId", new TextBox()},
             {"WG_Pic", new PictureBox()},
             {"WG_Type", new TextBox()},
             {"WG_Introduce", new RichTextBox()},
             {"WG_Count", new TextBox()},
             {"W_CExSentence", new RichTextBox()},
             {"WG_PublishTime", new TextBox(){Text=DateTime.Now.ToShortDateString()}}
             }
               );
            queryfile.Add(new WordGroupInf().GetType().ToString(),
            new Dictionary<string, string>{
             {"WG_Name", "like"},
             {"WG_WordId", "="},
             {"WG_Type", "like"},
             {"WG_PublishTime","like"}             
                }
                );
            //user
            LV_user.View = View.Details;
            LV_user.FullRowSelect = true;
            LV_user.HideSelection = false;
            controller.Add(LV_user, "usercontrol");
            model.Add(LV_user, new UserInf());
            LV_user.Columns.Add("id", 50, HorizontalAlignment.Center);
            LV_user.Columns.Add("登录id", 100, HorizontalAlignment.Center);
            LV_user.Columns.Add("密码", 100, HorizontalAlignment.Center);
            LV_user.Columns.Add("用户名", 100, HorizontalAlignment.Center);
            LV_user.Columns.Add("等级", 100, HorizontalAlignment.Center);
            LV_user.Columns.Add("头像", 100, HorizontalAlignment.Center);
            LV_user.Columns.Add("计划id", 100, HorizontalAlignment.Center);
            LV_user.Columns.Add("性别", 100, HorizontalAlignment.Center);
            LV_user.Columns.Add("记住单词集合", 100, HorizontalAlignment.Center);
            LV_user.Columns.Add("完成背单词天数", 100, HorizontalAlignment.Center);
            LV_user.Columns.Add("邮箱", 120, HorizontalAlignment.Center);
            LV_user.Columns.Add("注册时间", 150, HorizontalAlignment.Center);
            putcon.Add(new UserInf().GetType().ToString(),
             new Dictionary<string, Control>{
             {"U_Id",new TextBox()},
             {"U_LoginId", new TextBox()},
             {"U_Pwd", new TextBox()},
             {"U_Name", new TextBox()},
             {"U_Grade", new TextBox()},
             {"U_HeadPic", new PictureBox()},
             {"U_PlanId", new TextBox()},
             {"U_GenDer", new TextBox()},
             {"U_RemenberWord", new TextBox()},
             {"U_WorkDays", new TextBox()},
             {"U_Email", new TextBox()},
             {"U_RegisterTime", new TextBox()},
             }
               );
            queryfile.Add(new UserInf().GetType().ToString(),
            new Dictionary<string, string>{
             {"U_LoginId", "="},
             {"U_Name", "like"},
             {"U_Grade", "="},
             {"U_PlanId","="},
             {"U_GenDer","="},
             {"U_Email", "like"},
             {"U_RegisterTime","like"},   
                }
                );
            //plan
            LV_Plan.View = View.Details;
            LV_Plan.FullRowSelect = true;
            LV_Plan.HideSelection = false;
            controller.Add(LV_Plan, "plancontrol");
            model.Add(LV_Plan, new PlanInf());
            LV_Plan.Columns.Add("id", 50, HorizontalAlignment.Center);
            LV_Plan.Columns.Add("归属者id", 100, HorizontalAlignment.Center);
            LV_Plan.Columns.Add("计划每日单词数", 130, HorizontalAlignment.Center);
            LV_Plan.Columns.Add("已完成天数", 100, HorizontalAlignment.Center);
            LV_Plan.Columns.Add("已记住单词id", 100, HorizontalAlignment.Center);
            LV_Plan.Columns.Add("计划开始时间", 150, HorizontalAlignment.Center);
            LV_Plan.Columns.Add("单词组id", 100, HorizontalAlignment.Center);
            LV_Plan.Columns.Add("是否正在进行", 100, HorizontalAlignment.Center);
            LV_Plan.Columns.Add("已斩去单词", 100, HorizontalAlignment.Center);
            LV_Plan.Columns.Add("需复习的单词id", 100, HorizontalAlignment.Center);
            putcon.Add(new PlanInf().GetType().ToString(),
             new Dictionary<string, Control>{
             {"P_Id",new TextBox()},
             {"U_Id",new TextBox()},
             {"P_DayWork", new TextBox()},
             {"P_OverDay", new TextBox()},
             {"P_RemenberWord", new TextBox()},
             {"P_StarTime", new TextBox()},
             {"WG_id", new TextBox()},
             {"P_IsRead", new TextBox()},
             {"P_CutWord", new TextBox()},
             {"P_ReviewList", new TextBox()},
             }
               );
            queryfile.Add(new PlanInf().GetType().ToString(),
           new Dictionary<string, string>{
             {"U_Id","="},
             {"P_DayWork", "="},
             {"P_OverDay", "="},
             {"P_StarTime", "like"},
             {"WG_id", "="},
             {"P_IsRead", "="},
                }
               );
            //remenber
            LV_Remenber.View = View.Details;
            LV_Remenber.FullRowSelect = true;
            LV_Remenber.HideSelection = false;
            controller.Add(LV_Remenber, "remenbercontrol");
            model.Add(LV_Remenber, new RemenberInf());
            LV_Remenber.Columns.Add("id", 150, HorizontalAlignment.Center);
            LV_Remenber.Columns.Add("时间", 150, HorizontalAlignment.Center);
            LV_Remenber.Columns.Add("记住的数量", 100, HorizontalAlignment.Center);
            LV_Remenber.Columns.Add("记住单词的id集合", 130, HorizontalAlignment.Center);
            LV_Remenber.Columns.Add("还需复习id集合", 200, HorizontalAlignment.Center);
            LV_Remenber.Columns.Add("归属者", 100, HorizontalAlignment.Center);
            LV_Remenber.Columns.Add("所属计划", 100, HorizontalAlignment.Center);
            putcon.Add(new RemenberInf().GetType().ToString(),
             new Dictionary<string, Control>{
             {"R_Id",new TextBox()},
             {"R_Time",new TextBox()},
             {"R_RCount", new TextBox()},
             {"R_RWord", new TextBox()},
             {"R_EWord", new TextBox()},
             {"U_Id", new TextBox()},
             {"P_Id",new TextBox()}
             }
               );
            queryfile.Add(new RemenberInf().GetType().ToString(),
            new Dictionary<string, string>{
             {"R_Time","like"},
             {"R_RCount", "="},
             {"U_Id","="}
                }
               );
            //Admin
            LV_Admin.View = View.Details;
            LV_Admin.FullRowSelect = true;
            LV_Admin.HideSelection = false;
            controller.Add(LV_Admin, "admincontrol");
            model.Add(LV_Admin, new AdminInf());
            LV_Admin.Columns.Add("id", 50, HorizontalAlignment.Center);
            LV_Admin.Columns.Add("登录id", 100, HorizontalAlignment.Center);
            LV_Admin.Columns.Add("管理员名", 130, HorizontalAlignment.Center);
            LV_Admin.Columns.Add("登录密码", 100, HorizontalAlignment.Center);
            LV_Admin.Columns.Add("权限级别", 100, HorizontalAlignment.Center);
            LV_Admin.Columns.Add("注册时间", 150, HorizontalAlignment.Center);
            putcon.Add(new AdminInf().GetType().ToString(),
             new Dictionary<string, Control>{
            {"A_Id",new TextBox()},
            {"A_LoginId",new TextBox()},
            {"A_Pwd", new TextBox()},
            {"A_Name", new TextBox()},
            {"A_Power", new TextBox()},
            {"A_Time", new TextBox()}
             });
            queryfile.Add(new AdminInf().GetType().ToString(),
           new Dictionary<string, string>{
            {"A_LoginId","="},
            {"A_Name","like"},
            {"A_Power","="},
            {"A_Time", "like"}
                }
              );

        }
        /// <summary>
        /// 填充listView
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lv"></param>
        /// <param name="list"></param>
        private void LoadListView<T>(ListView lv, List<T> list)
        {
            if (list == null)
                return;
            lv.Items.Clear();
            foreach (T record in list)
            {
                ListViewItem item = new ListViewItem();
                int i = 0;
                foreach (System.Reflection.PropertyInfo inf in record.GetType().GetProperties())
                {
                    if (i == 0)
                        item.Text = inf.GetValue(record).ToString();
                    else
                        item.SubItems.Add(inf.GetValue(record) == null ? "" : inf.GetValue(record).ToString());
                    i++;
                }
                lv.Items.Add(item);
            }
        }
        /// <summary>
        /// 从指定的控制器方法中获取josn数据
        /// 反序列化后转换为list<T>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Url"></param>
        /// <returns></returns>
        private List<T> GetListDate<T>(string Url, Dictionary<string, string> param = null)
        {
            var url = BaseUrl + Url;
            AddLog("请求数据中");
            try
            {
                var redate = param == null ? HttpHelper.GetResponseString(HttpHelper.CreatePostHttpResponse(url, null, 100, "", null)) : HttpHelper.GetResponseString(HttpHelper.CreatePostHttpResponse(url, param, 100, "", null));
                return JSONHelper.JSONStringToList<T>(redate);
            }
            catch (Exception ex)
            {
                AddLog("请求数据失败!  url:" + url);
                return null;
            }
        }
        /// <summary>
        /// 添加状态日志
        /// </summary>
        /// <param name="log"></param>
        public void AddLog(object log)
        {
            RTB_status.Text += log.ToString() + "...." + DateTime.Now.ToShortTimeString() + "\n\r";
            RTB_status.SelectionStart = RTB_status.TextLength;
            RTB_status.ScrollToCaret();
        }
        /// <summary>
        /// 判断listview是否被选中了一条记录
        /// </summary>
        /// <param name="lv"></param>
        /// <returns></returns>
        private bool IsSelectOne(ListView lv)
        {
            if (lv.SelectedItems.Count != 1)
            {
                (new Message("请选中一条记录后再做操作")).ShowDialog();// MessageBox.Show("请选中一条记录后再做操作");
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取当前显示的listview
        /// </summary>
        /// <returns></returns>
        private ListView GetShowListView()
        {
            switch (TC_All.SelectedTab.Name)
            {
                case "TP_word":
                    return LV_word;
                case "TP_wordGroup":
                    return LV_Group;
                case "TP_User":
                    return LV_user;
                case "TP_plan":
                    return LV_Plan;
                case "TP_Remenber":
                    return LV_Remenber;
                case "TP_Admin":
                    return LV_Admin;
                default: throw new Exception("检查显示page");
            }
        }
        /// <summary>
        /// 递归清空窗体中的label和texbox控件
        /// </summary>
        /// <param name="con"></param>
        #region 内嵌窗体制作
        private void ClearFrom(Control con)
        {
            for (int i = 0; i < con.Controls.Count; i++)//判断界面上的控件 
            {
                Control obj5 = con.Controls[i];
                if (obj5.GetType().ToString() == "System.Windows.Forms.Label"
                    || obj5.GetType().ToString() == "System.Windows.Forms.TextBox"
                    || obj5.GetType().ToString() == "System.Windows.Forms.Button"
                    || obj5.GetType().ToString() == "System.Windows.Forms.RichTextBox"
                    || obj5.GetType().ToString() == "System.Windows.Forms.PictureBox") //如果控件是lable
                {
                    con.Controls.Remove(obj5);
                    i--;
                }
            }
        }
        /// <summary>
        /// 为内嵌窗体中添加labl和textbox
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="L_x"></param>
        /// <param name="L_y"></param>
        private int AddFieldUI(string name, string value, int L_x, int L_y, string chinese)
        {
            edit.Controls.Add(new Label() { Text = chinese, Location = new Point(L_x, L_y), Font = new Font("宋体", 12), Size = new Size(120, 16) });
            var putcontrol = putcon[model[GetShowListView()].GetType().ToString()][name];
            var controltype=putcontrol.GetType().ToString();
            if (controltype == "System.Windows.Forms.TextBox"||controltype == "System.Windows.Forms.RichTextBox")
                AlertTextBoxUI(controltype,putcontrol);
            if (controltype == "System.Windows.Forms.Button")
                AlertButtonUI( putcontrol);
            putcontrol.Name = "Tb_" + name;
            var py = L_y + 8 - putcontrol.Height * 0.5;
            putcontrol.Location = new Point(120 + L_x, Convert.ToInt32(py));
            putcontrol.Text = value; //   == "" ? putcontrol.Text : value;//  测试使用
            //播放视频button处理
            if(controltype == "System.Windows.Forms.Button" && putcontrol.Tag as Play != null)
            {
                putcontrol.Text = "播放视频";
                (putcontrol.Tag as Play).interneturl=VideoBase + value;
                putcontrol.Click += edit.ShowVideo;
                //添加按钮
                Button bt = new Button();
                bt.Tag = putcontrol;
                bt.Name = "Bt_Up" + name;
                bt.Text = "修改视频";
                try
                {
                    bt.Click -= new EventHandler(edit.UpMp4);
                }
                finally
                {
                    bt.Click += new EventHandler(edit.UpMp4);
                }
                bt.Location = new Point(putcontrol.Location.X + putcontrol.Width + 10, putcontrol.Location.Y);
                AlertButtonUI(bt);
                edit.Controls.Add(bt);
                //异步取视频
                GitPicdeletegate dtgetvideo = new GitPicdeletegate(GetFile);
                AsyncCallback callback = new AsyncCallback(GetVideoBack);
                if (value == "")//判断是否有路径
                {
                    edit.Controls.Add(putcontrol);
                    return L_y + putcontrol.Height;
                }
                dtgetvideo.BeginInvoke(value, ".mp4", callback, putcontrol);
            }
            //播放音乐button处理
            if (controltype == "System.Windows.Forms.Button"&&putcontrol.Tag as Dictionary<string,string>!=null)
            {
                putcontrol.Text = "";
                (putcontrol.Tag as Dictionary<string, string>)["server"] = value;
                putcontrol.Click += new EventHandler(edit.Button_PlayMusic);//GetMusicBack
                //添加按钮
                Button bt = new Button();
                bt.Tag = putcontrol;
                bt.Name = "Bt_Up" + name;
                bt.Text = "修改文件";
                try
                {
                    bt.Click -= new EventHandler(edit.UpMp3);
                }
                finally
                {
                    bt.Click += new EventHandler(edit.UpMp3);
                }
                bt.Location = new Point(putcontrol.Location.X +putcontrol.Width +10, putcontrol.Location.Y+Convert.ToInt32(putcontrol.Height*0.5));
                AlertButtonUI(bt);
                edit.Controls.Add(bt);
                //异步获取音频
                GitPicdeletegate dtgetpic = new GitPicdeletegate(GetFile);
                AsyncCallback callback = new AsyncCallback(GetMusicBack);
                if (value == "")//判断是否有路径
                {
                    edit.Controls.Add(putcontrol);
                    return L_y + putcontrol.Height;
                }
                //var  pt=putcontrol.Tag as  Dictionary<string,string>;//789*
                dtgetpic.BeginInvoke(value,".mp3", callback, putcontrol);//参数为给处理函数参数，回调函数，回调函数参数
            }
            //PictureBox处理
            if (controltype == "System.Windows.Forms.PictureBox")
            {
                ((PictureBox)putcontrol).Image = Image.FromFile(Application.StartupPath + @"\pic\"+"bcz.png");
                ((PictureBox)putcontrol).SizeMode = PictureBoxSizeMode.StretchImage;
                //异步获取图片
                GitPicdeletegate dtgetpic = new GitPicdeletegate(GetFile);
                AsyncCallback callback = new AsyncCallback(GetPicBack);
                //清空绑定
                try
                {
                    ((PictureBox)putcontrol).Click -= new EventHandler(edit.Uppic);

                }
                finally
                {
                    ((PictureBox)putcontrol).Click += new EventHandler(edit.Uppic);
                }
                if (value == "")//判断是否有路径
                {
                    edit.Controls.Add(putcontrol);
                    return L_y + putcontrol.Height;
                }
                dtgetpic.BeginInvoke(value,".jpg", callback, putcontrol);//参数为给处理函数参数，回调函数，回调函数参数
                ((PictureBox)putcontrol).Tag = value;
            }
            edit.Controls.Add(putcontrol);
            return L_y + putcontrol.Height;
        }
        /// <summary>
        /// 为内嵌的button添加button
        /// </summary>
        /// <param name="L_x"></param>
        /// <param name="L_y"></param>
        /// <param name="name"></param>
        /// <param name="name2"></param>
        private void AddButton(int L_x, int L_y, string name, string type)
        {
            var bt_op = new Button() { Name = "BT_" + name, Text = name, Location = new Point(L_x, L_y), Size = new Size(75, 23) };
            var bt_re = new Button() { Name = "BT_reset", Text = "重置", Location = new Point(L_x + 120, L_y), Size = new Size(75, 23) };
            edit.Controls.Add(bt_op);
            edit.Controls.Add(bt_re);
            switch (type)
            {
                case "alert":
                    edit.Controls.Find("BT_" + name, true)[0].Click += new EventHandler(edit.Alert);
                    break;
                case "add":
                    edit.Controls.Find("BT_" + name, true)[0].Click += new EventHandler(edit.Add);
                    break;
                case "query":
                    edit.Controls.Find("BT_" + name, true)[0].Click += new EventHandler(edit.Query);
                    break;
                default: throw new Exception("错误的type值");
            }
            AlertButtonUI(bt_op);
            AlertButtonUI(bt_re);
            edit.Controls.Find("BT_reset", true)[0].Click += edit.reset;
        }
        /// <summary>
        /// 填充内嵌窗体
        /// </summary>
        /// <param name="lv"></param>
        /// <param name="isalert">是否给texbox加值</param>
        #endregion
        private void makeForm(ListView lv, string type)
        {
            //清理
            ClearFrom(edit);
            edit.Dock = DockStyle.Fill;//edit窗体填满panel
            var dx = model[lv];
            edit.type = dx;
            edit.control = controller[lv];//设置控制器值
            int i = 0;
            var X = x;//应用设置的初始值
            var Y = y;
            if (type == "query")
            {
                var list = queryfile[dx.GetType().ToString()];
                foreach (System.Reflection.PropertyInfo p in dx.GetType().GetProperties())
                {
                    if (list.ContainsKey(p.Name))
                    {
                        Y = AddFieldUI(p.Name, "", X, Y, lv.Columns[i].Text);
                        Y += YDistance;
                    }
                    i++;
                }
                AddButton(X, Y + 10, "查询", type);
            }
            else if (type == "alert" || type == "add")
            {
                foreach (System.Reflection.PropertyInfo p in dx.GetType().GetProperties())
                {
                    Y = AddFieldUI(p.Name, type == "alert" ? lv.SelectedItems[0].SubItems[i].Text : "", X, Y, lv.Columns[i].Text);
                    Y += YDistance;
                    i++;
                }
                AddButton(X, Y + 10, type == "alert" ? "修改" : "添加", type);
            }
            else
            {
                throw new Exception("错误的type值");
            }
            edit.ChangeSize(edit.Size.Width, Y + 180);//改变自身窗体大小是panle出现滚动条
        }
        #region  增删改查
        private void BT_add_Click(object sender, EventArgs e)
        {
            var lv = GetShowListView();
            makeForm(lv, "add");
        }
        private void BT_Alert_Click(object sender, EventArgs e)
        {
            var lv = GetShowListView();
            if (IsSelectOne(lv))
                makeForm(lv, "alert");
        }
        private void BT_delet_Click(object sender, EventArgs e)
        {
            var lv = GetShowListView();
            if (!IsSelectOne(lv))
                return;
            if (CB_del.Checked == true ? true : (DialogResult.OK == (new MessageShowcs("确实要删除吗？")).ShowDialog()))
            {
                Dictionary<string, string> josninf = new Dictionary<string, string>();
                josninf.Add("rdid", lv.SelectedItems[0].SubItems[0].Text);
                AddLog(HttpHelper.GetResponseString(HttpHelper.CreatePostHttpResponse(BaseUrl + "/" + controller[lv] + "/" + "delet", josninf, 100, "", null)) == "true" ? "删除成功" : "删除失败");
                LoadPage("getall");
                return;
            }
            AddLog("放弃了删除");
        }
        private void BT_query_Click(object sender, EventArgs e)
        {
            makeForm(GetShowListView(),"query");
        }
        #endregion
        private string GetFile(string url,string typename)
        {
           WebClient client = new WebClient();
           Random rd = new Random();
           m_SyncContext.Post(AddLog,"获取"+Filetype[typename]+"文件中");
           if (!Directory.Exists(Application.StartupPath + @"\" + "temp"))
               Directory.CreateDirectory(Application.StartupPath + @"\" + "temp");
           var filesavepath = Application.StartupPath + @"\" + "temp" + @"\" + rd.Next().ToString() + typename;
            try
            {
                switch (typename)
                {
                    case ".mp3": client.DownloadFile(MusicBase + url, filesavepath); break;
                    case ".jpg": client.DownloadFile(PicBase + url, filesavepath); break;
                    case ".mp4": client.DownloadFile(VideoBase + url, filesavepath); break;
                    default: (new Message("错误的类型")).ShowDialog(); break;
                }
               
            }
            catch (Exception ex)
            {
                m_SyncContext.Post(AddLog, Filetype[typename]+ "文件没有获取成功");
                return "";
            }
            return filesavepath;
        }
        #region 获取文件的回掉
        private void GetPicBack(IAsyncResult result)
        {
            //获取异步调用的委托
            AsyncResult defaultpath = (AsyncResult)result;//异步操作的结果
            GitPicdeletegate T = (GitPicdeletegate)defaultpath.AsyncDelegate;//获取委托对象
            PictureBox putcontrol = (PictureBox)result.AsyncState;//获取回掉函数的参数
            //处理结束
            string answer = T.EndInvoke(result);//委托方法执行后的返回结果
            if (answer != "")
            {
                ((PictureBox)putcontrol).Image = Image.FromFile(answer);
                ((PictureBox)putcontrol).SizeMode = PictureBoxSizeMode.StretchImage;
                m_SyncContext.Post(AddLog, "图片加载成功");
            }
        }
        private void GetMusicBack(IAsyncResult result)
        {
            //获取异步调用的委托
            AsyncResult defaultpath = (AsyncResult)result;//异步操作的结果
            GitPicdeletegate T = (GitPicdeletegate)defaultpath.AsyncDelegate;//获取委托对象
            Button putcontrol = (Button)result.AsyncState;//获取回掉函数的参数
            //处理结束
            string answer = T.EndInvoke(result);//委托方法执行后的返回结果
            if (answer != "")
            {
                var dic= putcontrol.Tag as Dictionary<string,string>;
                dic["local"] = answer;
                m_SyncContext.Post(AddLog, "音频加载成功");
            }
        }
        private void GetVideoBack(IAsyncResult result)
        {
            AsyncResult defaultpath = (AsyncResult)result;//异步操作的结果
            GitPicdeletegate T = (GitPicdeletegate)defaultpath.AsyncDelegate;//获取委托对象
            Button putcontrol = (Button)result.AsyncState;//获取回掉函数的参数
            string answer = T.EndInvoke(result);//委托方法执行后的返回结果
            if (answer != "")
            {
                Play dic = putcontrol.Tag as Play;
                dic.localurl = answer;
                m_SyncContext.Post(AddLog, "视频加载成功");
            }
        }
        #endregion
        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            //清空临时文件
            try
            {
                Directory.Delete(Application.StartupPath + @"\" + "temp", true);
                Directory.CreateDirectory(Application.StartupPath + @"\" + "temp");
            }
            catch { }
        }
        private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            //為當前的應用程序釋放鼠標鋪獲
            ReleaseCapture();
            //發送消息﹐讓系統誤以為在标题栏上按下鼠標
            SendMessage((int)this.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
        }
        private void TC_All_DrawItem(object sender, DrawItemEventArgs e)
        {
            SolidBrush black = new SolidBrush(Color.FromArgb(34, 34, 35));
            SolidBrush wite = new SolidBrush(Color.FromArgb(93, 140, 174));
            for (int i = 0; i < TC_All.TabPages.Count; i++)
            {
                Rectangle  r= TC_All.GetTabRect(i);
                var font = new StringFormat();
                font.Alignment=StringAlignment.Center;
                e.Graphics.FillRectangle(black,r);//背景色
                e.Graphics.DrawString(TC_All.TabPages[i].Text, new Font("宋体", 10),wite,r,font);
            }
        }
        private void BT_out_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == (new MessageShowcs("确实要退出吗？")).ShowDialog())
            {
                //窗体弹出效果
                AnimateWindow(this.Handle, 300, AW_HIDE + AW_CENTER);
                Application.Exit();
            }
        }
        private void AlertTextBoxUI(string type,Control putcontrol)
        {
            switch (type)
            {
                case  "System.Windows.Forms.TextBox":
                (putcontrol as TextBox).BackColor = Color.FromArgb(51, 51, 55);
                (putcontrol as TextBox).BorderStyle = BorderStyle.None;
                (putcontrol as TextBox).ForeColor = Color.Wheat;
                    break;
                case  "System.Windows.Forms.RichTextBox":
                (putcontrol as RichTextBox).BackColor = Color.FromArgb(51, 51, 55);
                (putcontrol as RichTextBox).BorderStyle = BorderStyle.None;
                (putcontrol as RichTextBox).ForeColor = Color.Wheat;
                    break;
                default :break;
            }
        }
        private void AlertButtonUI(Control putcontrol)
        {
            (putcontrol as Button).FlatStyle = FlatStyle.Flat;
            (putcontrol as Button).BackColor = Color.FromArgb(34, 34, 34);
            (putcontrol as Button).ForeColor = Color.FromArgb(93, 140, 174);
        }
        /// <summary>
        /// 按钮点击改变Tabpage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonChangeTab(object sender, EventArgs e)
        {
            switch ((sender as Button).Name)
            {
                case "BT_word":
                    TC_All.SelectedIndex = 0;
                    ; break;
                case "BT_plan":
                    TC_All.SelectedIndex = 3;
                    ; break;
                case "BT_remenber":
                    TC_All.SelectedIndex = 4;
                    ; break;
                case "BT_wordgroup":
                    TC_All.SelectedIndex = 1;
                    ; break;
                case "BT_admin":
                    TC_All.SelectedIndex = 5;
                    ; break;
                case "BT_user":
                    TC_All.SelectedIndex = 2;
                    ; break;
                default:throw new Exception("错误") ; break;
            }
        
        }
    }
}
